<template>
    <view class="confirm-main">
        <view class="confirm-content">
            <HeaderTab @tabChange="tabChangeHandler"></HeaderTab>
            <GroupSteps v-if="props.orderType == 3" />
            <view v-if="Data.tabValue === 0" class="address" @click="jumpAddress()">
                <view class="no-address" v-if="!Data.addressId">
                    <view class="no-address-text">请选择收货地址</view>
                    <view class="no-address-desc">请先添加收货地址</view>
                </view>
                <view v-else>
                    <view class="address-text">
                        <view class="address-text-area">
                            {{ Data.addressInfo.provinceName }}
                            {{ Data.addressInfo.cityName }}
                            {{ Data.addressInfo.areaName }}
                            {{ Data.addressInfo.townName }}
                        </view>
                        <view class="address-text-address"> {{ Data.addressInfo.street }} </view>
                        <view class="address-phone">{{ Data.addressInfo.realName }} {{ Data.addressInfo.mobile }}</view>
                    </view>
                </view>
                <view class="address-icon-img">
                    <image :src="getImgOssUrl('/ui-prod-2.0.0/icon_img05.png')" />
                </view>
            </view>
            <Address
                v-if="Data.tabValue === 1"
                :showDistance="true"
                :canChange="Data.siteListLength !== 1"
                :addressInfo="Data.selfAddressInfo"></Address>
            <!-- here: 联系人、手机号默认使用下单人昵称和手机号，支持修改 -->
            <view v-if="Data.tabValue === 1" class="other-info">
                <view class="other-info-item">
                    <view>联系人</view>
                    <view class="other-info-item-right">
                        <input
                            :maxlength="20"
                            v-model="Data.consignee"
                            :cursor-spacing="75"
                            placeholder="请输入联系人" />
                    </view>
                </view>
                <view class="other-info-item">
                    <view>手机号</view>
                    <view class="other-info-item-right">
                        <input
                            v-model="Data.consigneeMobile"
                            :maxlength="11"
                            :cursor-spacing="75"
                            placeholder="请输入手机号" />
                    </view>
                </view>
            </view>

            <view class="goods" v-for="(item, index) in Data.goodsList" :key="`k${index}`">
                <GoodsCard :orderType="props.orderType" :goodsData="item" :showGoodsTag="true" />
            </view>
            <view class="other-info">
                <view class="other-info-item">
                    <view>商品总价</view>
                    <view class="other-info-item-right">
                        <text v-if="props.orderType == 6">
                            <text v-if="Data.confirmInfo.price > 0">
                                {{ floatDivide(Data.confirmInfo.price, 100) }}元+</text
                            ><text>{{ floatDivide(Data.confirmInfo.totalPoints, 100) }}积分</text>
                        </text>
                        <text v-else>￥{{ floatDivide(Data.confirmInfo.price, 100) }}</text>
                    </view>
                </view>
                <!-- 积分商城订单有三种 需要显示 -->
                <view v-if="props.orderType == 6" class="other-info-item">
                    <view>积分抵扣</view>
                    <view class="other-info-item-right">
                        <text>-{{ floatDivide(Data.confirmInfo.totalPoints, 100) }}积分 </text>
                    </view>
                </view>
                <!-- <view v-if="Data.confirmInfo.activity?.id" class="other-info-item"> -->
                <view v-if="[2, 3].includes(Number(props.orderType))" class="other-info-item">
                    <view>活动优惠_{{ getActivityType() }}</view>
                    <view class="other-info-item-right price">
                        <text>-￥{{ getPrice() }}</text>
                    </view>
                </view>
                <!-- 返回的fullReduceDiscount是字符串 -->
                <view class="other-info-item" v-if="Number(Data.confirmInfo?.fullReduceDiscount)">
                    <view>满减优惠</view>
                    <view class="other-info-item-right price">
                        <text>-￥{{ floatDivide(Data.confirmInfo.fullReduceDiscount, 100) }}</text>
                    </view>
                </view>
                <view class="other-info-item" v-if="Number(props.orderType) !== 6">
                    <view>优惠券优惠</view>
                    <view v-if="props.orderType == 2 || state.useCouponFlag == 1" class="other-info-item-right">
                        <text class="placeholder">不支持使用优惠券</text>
                    </view>
                    <view v-else class="other-info-item-right" @click="toCoupon">
                        <text class="placeholder" v-if="!Data.isCoupon">暂无可用优惠券</text>
                        <text class="placeholder" v-else-if="Data.isCoupon && Data.customerCouponId == -1">
                            {{ Data.couponList.length }}张可用
                        </text>
                        <text v-else class="price">-￥{{ floatDivide(Data.couponFee, 100) }}</text>
                        <image class="img-icon" :src="getImgOssUrl('/ui-prod-2.0.0/rightarrow1.1.png')"></image>
                    </view>
                </view>
                <!-- 普通订单显示积分抵扣（ordinary_order：普通订单；credit_offset_goods：积分抵扣订单） -->
                <view
                    class="other-info-item"
                    v-if="Data.confirmInfo.orderCategory === 'credit_offset_goods' || !Data.usePoint"
                    @click="showPopup('point')">
                    <view>积分抵扣</view>
                    <view class="other-info-item-right" v-if="Data.confirmInfo?.creditCashOrder?.proPointsFlag == 1">
                        <text class="placeholder">积分不足&nbsp;</text>
                    </view>
                    <view class="other-info-item-right price" v-else>
                        <text v-show="Data.usePoint">
                            -￥{{ floatDivide(Data.confirmInfo.discountPropReducePrice, 100) }}&nbsp;
                        </text>
                        <text class="placeholder" v-show="!Data.usePoint">暂不使用&nbsp;</text>
                        <image class="cell-icon-img" :src="getImgOssUrl('/ui-prod-2.0.0/icon_img05.png')" />
                    </view>
                </view>
                <!-- here: 上门自提没有运费 -->
                <view v-if="Data.tabValue !== 1" class="other-info-item">
                    <view>运费</view>
                    <view v-if="hasFreeShipping" class="other-info-item-right">会员包邮</view>
                    <view v-else class="other-info-item-right">
                        ￥{{ floatDivide(Data.confirmInfo.logisticsFee, 100) }}
                    </view>
                </view>
            </view>
            <view @click="showPopup('remark')" class="remark">
                <view class="remark-label">备注</view>
                <view>
                    <text class="remark-content" v-if="Data.remarks">{{ Data.remarks }}</text>
                    <text class="remark-content-none" v-else>暂无备注</text>
                    <image class="cell-icon-img ver-top" :src="getImgOssUrl('/ui-prod-2.0.0/icon_img05.png')" />
                </view>
            </view>
            <!-- 用来占位 -->
            <view class="occupy"></view>
        </view>
        <view class="pay-footer">
            <view class="pay-footer-info">
                <view>
                    <text class="pay-footer-info-text">应付</text>
                    <text class="pay-footer-info-price">
                        <text class="pay-footer-info-icon">￥</text>
                        <text>{{ floatDivide(Data.confirmInfo.orderAmountTotal, 100) }}</text>
                    </text>
                </view>
                <view
                    class="pay-button"
                    :class="{ 'pay-button-disabled': !checkOrderIsReady }"
                    @click="beforePayValide">
                    提交订单
                </view>
            </view>
        </view>
        <!-- <view class="out-stock-popup" v-if="stockPopShow">
            <view class="out-stock-content">
                <view class="stock-title">{{ Data.stockPopText }}</view> -->
        <!-- 该地区以下商品缺货，请返回购物车重新下单！ -->
        <!-- <view class="stock-list">
                    <image
                        class="stock-img"
                        :src="item.coverSrc"
                        v-for="(item, index) in Data.stockList"
                        :key="index"></image>
                </view>
                <view class="button" @click="clickStock">确定</view>
            </view>
        </view> -->
        <!-- 库存不足取消订单 -->
        <MessageBox
            ref="messagebox"
            :content="Dialog.content"
            btnName="取消订单"
            @comfirm="cancelOrderConfirm"></MessageBox>
        <!-- 弹窗 -->
        <uni-popup type="bottom" ref="popup" :safe-area="false">
            <view class="popup-bg">
                <image
                    class="close-img"
                    @click="popup.close()"
                    :src="getImgOssUrl('/ui-prod-2.0.0/cancel_1.1.png')"></image>
                <view class="popup-title">{{ popupData.title }}</view>
                <view v-if="popupData.type === 'remark'">
                    <textarea
                        class="remark-text"
                        placeholder="请填写备注信息，不超过200字"
                        v-model="popupData.remark"
                        maxlength="200" />
                </view>
                <view class="point-part" v-if="popupData.type === 'point'">
                    <view class="point-item" @click="choosePoint(1)">
                        <view>积分抵现</view>
                        <view>
                            <text class="point-num"> -￥{{ floatDivide(Data.maxPointReduce, 100) }} </text>
                            <image
                                v-show="!popupData.hidePoint"
                                class="img"
                                :src="getImgOssUrl('/ui-prod-2.6.0/checked@2x.png')" />
                            <image
                                v-show="popupData.hidePoint"
                                class="img"
                                :src="getImgOssUrl('/ui-prod-2.6.0/check@2x.png')" />
                        </view>
                    </view>
                    <view class="point-item" @click="choosePoint(0)">
                        <view>不使用</view>
                        <view>
                            <image
                                v-show="popupData.hidePoint"
                                class="img"
                                :src="getImgOssUrl('/ui-prod-2.6.0/checked@2x.png')" />
                            <image
                                v-show="!popupData.hidePoint"
                                class="img"
                                :src="getImgOssUrl('/ui-prod-2.6.0/check@2x.png')" />
                        </view>
                    </view>
                </view>
                <view class="popup-btn" @click="closePopup(popupData.type)">确定</view>
            </view>
        </uni-popup>
        <dialogCoupon :visiable="Data.showCoupon" @select="closeCouponDialog()"></dialogCoupon>
        <Loading />
        <!-- 隐私监听 -->
        <el-privacy-listener-popup></el-privacy-listener-popup>
    </view>
</template>
<script setup>
import GroupSteps from './groupSteps';
import HeaderTab from '@/components/headerTab';
import Address from '@/components/address';
import GoodsCard from '@/components/goodsCard';
import MessageBox from '@/components/messageBox';
import dialogCoupon from './popup/coupon.vue';
import { ref, reactive, computed, inject } from 'vue';
import { onShow, onUnload } from '@dcloudio/uni-app';
import { floatDivide, floatMultiply, getImgOssUrl, isMobile } from '@/commons/utils.js';
import request from '@/request';
import router from '@/router';
import store from '@/store';
import storage from '@/commons/storage';
import Loading from '@/components/el-loading';
import { useTrace } from '@/commons/trace';
import subscribe from '@/commons/subscribe';

const { traceReport } = useTrace();
const goodsStore = store.useGoodsStore();

const props = defineProps({
    type: {
        type: Number,
        default: 1
    },
    skuList: {
        type: String,
        default: ''
    },
    cardIds: {
        type: String,
        default: ''
    },
    activityId: {
        type: [String, Number]
    },
    spellOrderId: {
        type: String
    },
    spellNum: {
        type: String
    },
    orderType: {
        type: [String, Number],
        default: 1
    }
});
// 是否有会员包邮权益
const hasFreeShipping = ref(false);
const userAvailablePoints = ref(0);
const currency = inject('currency');
const state = reactive({
    // discountRepeat: 2, // 优惠叠加 1-不叠加 2-叠加
    // spellGroupMail: 2, // 拼团包邮 1-不包邮 2-包邮
    spellOrderId: 0, // 拼团订单id
    //1暂不支持使用优惠券 默认。 无任何逻辑
    useCouponFlag: 0
});

const Data = reactive({
    skuList: (props.skuList && JSON.parse(props.skuList)) || [],
    cartIds: (props.cardIds && JSON.parse(props.cardIds)) || [],
    allAmount: 0,
    confirmInfo: {},
    addressInfo: {},
    selfAddressInfo: {},
    consignee: '',
    consigneeMobile: '',
    goodsList: [],
    activity: {
        activityGoods: []
    },
    addressId: '',
    orderSn: '',
    orderId: '',
    stockList: [],
    remarks: '',
    stockPopText: '',
    canLogistics: 1,
    customerCouponId: '',
    couponInfo: {},
    isCoupon: false,
    showCoupon: false,
    couponList: [],
    // 配送方式
    tabValue: 0,
    // 自提点id
    siteId: null,
    siteListLength: 0,
    usePoint: true
});

const messagebox = ref();
const Dialog = reactive({
    content: ''
});

// 弹出框
const popup = ref();
const popupData = reactive({
    title: '',
    type: '',
    hidePoint: '',
    remark: ''
});

// 是否可以提交订单
const checkOrderIsReady = computed(() => {
    return (Data.tabValue === 0 && Data.addressId) || (Data.tabValue === 1 && Data.siteId);
});

// 获取确认订单默认走这里
const tabChangeHandler = val => {
    Data.tabValue = val;
    switch (val) {
        case 0:
            getAddressList();
            break;
        case 1:
            if (!Data.siteId) {
                getDefalutSelfPick();
            } else {
                getConfirm();
            }
            break;
        default:
            break;
    }
};

const queryMaxPointReduce = async () => {
    let params = {
        skuList: Data.skuList,
        type: props.type,
        addressId: Data.addressId,
        cartId: Data.cartIds,
        customerCouponId: Data.customerCouponId,
        isPointsGoods: props.orderType == 6 ? 1 : 0,
        isPropReduce: 1
    };
    let data = await request('confirmOrderServ', params);
    Data.maxPointReduce = data.data.discountPropReducePrice;
};

// 和购物车列表顺序保持一致
const sortHandle = list => {
    return Data.skuList.map(item => list.find(it => item.skuId === it.skuId)).filter(Boolean);
};
const getConfirm = async () => {
    let params = {
        skuList: Data.skuList,
        type: props.type,
        addressId: Data.tabValue === 0 ? Data.addressId : 0,
        siteId: Data.tabValue === 1 ? Data.siteId : 0,
        cartId: Data.cartIds,
        customerCouponId: Data.customerCouponId,
        isPointsGoods: props.orderType == 6 ? 1 : 0,
        isPropReduce: Number(Data.usePoint)
    };
    if (props.activityId) {
        params.activityId = +props.activityId;
    }
    if (props.spellNum) {
        params.spellNum = props.spellNum;
    }
    let res = await request('confirmOrderServ', params);
    // switch (props.orderType) {
    //     case '2':
    //         state.discountRepeat = 1;
    //         break;
    //     case '3':
    //         state.discountRepeat = res.data.activity.spellActivityGroupInfo.discount_repeat;
    //         state.spellGroupMail = res.data.activity.spellActivityGroupInfo.spell_group_mail;
    //         break;
    // }
    state.useCouponFlag = res.data.useCouponFlag;
    Data.confirmInfo = res.data;
    Data.allAmount = Number(res.data.logisticsFee) + Number(res.data.price);
    Data.addressInfo = res.data.addressInfo || {};
    if (!Data.addressInfo?.realName) {
        Data.addressId = 0;
        goodsStore.addressId = '';
    }
    const list = sortHandle(res.data.skuList);
    Data.goodsList = rebuildSkuList(list);
    // Data.goodsList = rebuildSkuList(res.data.skuList);
    Data.activity = res.data.activity || [];
    Data.couponList = res.data.couponList || [];
    let couponList = Data.couponList;
    let couponInfo = res.data.canUseCouponInfo || {};
    Data.couponInfo = couponInfo;
    Data.couponFee = res.data.couponFee;
    Data.customerCouponId = params.customerCouponId == -1 ? -1 : couponInfo.customerCouponId;
    couponList.map(el => {
        if (el.customerCouponId == couponInfo.customerCouponId) {
            el.active = true;
        } else {
            el.active = false;
        }
    });
    goodsStore.couponList = couponList;
    if (couponList.length) {
        Data.isCoupon = true;
    }
    if (res.data.canBuy === 0 && Data.tabValue === 0) {
        if (res.data.errorMsg) {
            Data.stockPopText = res.data.errorMsg;
            Data.stockList = Data.goodsList;
        } else {
            let info = Data.goodsList.find(el => el.canBuy == 0) || {};
            Data.stockList = [info];
            Data.stockPopText = info.errorMsg;
        }
    }
};

const rebuildSkuList = (arr = []) => {
    return arr.map(x => {
        return Object.assign(x, {
            goodsImg: x.coverSrc,
            goodsNum: x.quantity,
            goodsPrice: x.skuPrice
        });
    });
};

const getActivityType = () => {
    switch (props.orderType) {
        case '2':
            return '秒杀';
        case '3':
            return '拼团';
    }
};
const getPrice = () => {
    switch (props.orderType) {
        case '2':
            return currency(Data.confirmInfo.secKillActivityDiscount).divide(100).value;
        case '3':
            return currency(Data.confirmInfo.spellActivityDiscount).divide(100).value;
    }
};

const queryUserInfo = async () => {
    const currentDetail = await request('management', { openKid: storage.get('openKid'), appType: 1 });
    const priority = currentDetail?.data?.priority || [];
    hasFreeShipping.value = !!priority.find(x => x.default === 1 && x.priorityType === 1);
    userAvailablePoints.value = currentDetail.data?.points?.availablePoints;
    Data.consignee = currentDetail?.data?.nickname;
    Data.consigneeMobile = currentDetail?.data?.mobile;
};
queryUserInfo();

const getAddressList = async () => {
    let res = await request('addressListServ');
    if (res.data.length) {
        // 默认地址是第一个
        Data.addressId = res.data[0]?.id;
    }
    getConfirm();
};

const setAddressInfo = async () => {
    let params = {
        realName: Data.addressInfo.realName,
        mobile: Data.addressInfo.mobile,
        provinceId: Data.addressInfo.nationalCode.substr(0, 2),
        cityId: Data.addressInfo.nationalCode.substr(2, 2),
        areaId: Data.addressInfo.nationalCode.substr(4, 2),
        townId: '',
        street: Data.addressInfo.street,
        consigneeZip: Data.addressInfo.consigneeZip,
        wechat: 2
    };
    let res = await request('saveAddressListServ', params);
    if (res.data) {
        Data.addressId = res.data?.id;
        getConfirm();
    }
};

const getSpecValue = list => {
    let ary = [];
    let str = '';
    list &&
        list.map(el => {
            // ary.push(`${el.keyAttributeName}：${el.attributeValue}`);
            ary.push(el.attributeValue);
        });
    str = ary.join(';');
    return str;
};

const jumpAddress = async () => {
    const res = await request('addressListServ');
    if (res?.data?.length) {
        router.push({
            path: '/pages-user/receiptAddress/list',
            query: {
                from: 'order'
            }
        });
    } else {
        uni.chooseAddress({
            success(res) {
                Data.addressInfo.provinceName = res.provinceName;
                Data.addressInfo.cityName = res.cityName;
                Data.addressInfo.areaName = res.countyName;
                Data.addressInfo.street = res.detailInfo;
                Data.addressInfo.realName = res.userName;
                Data.addressInfo.mobile = res.telNumber;
                Data.addressInfo.nationalCode = res.nationalCode;
                Data.addressInfo.consigneeZip = res.postalCode;
                setAddressInfo();
            }
        });
    }
};

// const clickStock = () => {
//     if (Data.stockList.some(el => el.errorCode == 10510004)) {
//     } else {
//         router.back();
//     }
// };

// 打开弹框
const showPopup = type => {
    popupData.type = type;
    switch (type) {
        case 'remark':
            popupData.title = '订单备注';
            popupData.remark = Data.remarks;
            break;
        case 'point':
            if (Data.confirmInfo?.creditCashOrder?.proPointsFlag == 1) {
                return;
            } else {
                if (Number(Data.usePoint) === 0) {
                    queryMaxPointReduce();
                } else {
                    Data.maxPointReduce = Data.confirmInfo.discountPropReducePrice;
                }
                popupData.title = '使用积分抵现';
                popupData.hidePoint = !Data.usePoint;
            }
            break;
        default:
            break;
    }
    popup.value.open();
};

// 点击确认关闭弹框
const closePopup = type => {
    switch (type) {
        case 'remark':
            Data.remarks = popupData.remark;
            break;
        case 'point':
            Data.usePoint = !popupData.hidePoint;
            getConfirm();
            break;
        default:
            break;
    }
    popup.value.close();
};

// 切换是否使用积分兑换
const choosePoint = val => {
    popupData.hidePoint = !val;
};

const toCoupon = () => {
    Data.showCoupon = true;
};

// 进店逛逛
const toHome = () => {
    router.switchTab({ url: '/pages/tabbar/home' });
};
// 重新参与
const toGoodsDetail = () => {
    router.push({
        path: '/pages-cart/good/index',
        query: {
            activityId: props.activityId,
            goodsId: Data.skuList[0].goodsId
        }
    });
};

let orderFlag = ref(false);
let firstSubmit = ref(1);
const beforePayValide = () => {
    let stopOrder = null;
    let timeId = null;
    if (firstSubmit.value === 1) {
        firstSubmit.value++;
        orderFlag.value = true;
        payValide();
        stopOrder = setInterval(() => {
            clearInterval(stopOrder);
            orderFlag.value = false;
        }, 5000);
    } else {
        if (orderFlag.value) {
            uni.showToast({
                title: '订单提交中...',
                icon: 'none'
            });
            return;
        }
        orderFlag.value = true;
        payValide();
        timeId = setInterval(() => {
            clearInterval(timeId);
            orderFlag.value = false;
        }, 5000);
    }
};

const orderSubmit = async () => {
    let params = {
        skuList: Data.skuList,
        purchaseData: Data.confirmInfo,
        addressId: Data.tabValue === 0 ? Data.addressId : 0,
        cartIds: Data.cartIds,
        customerCouponId: Data.customerCouponId,
        remarks: Data.remarks,
        isPointsGoods: props.orderType == 6 ? 1 : 0,
        isPropReduce: Number(Data.usePoint),
        // 自提点id
        siteId: Data.tabValue === 1 ? Data.siteId : 0,
        consignee: Data.consignee,
        consigneeMobile: Data.consigneeMobile
    };
    if (props.orderType == 3) {
        params.spellNum = +props.spellNum;
    }
    if (props.spellOrderId) {
        params.spellOrderId = +props.spellOrderId;
    }
    if (props.activityId) {
        params.activityId = props.activityId;
    }
    request('orderPurchaseServ', params)
        .then(res => {
            Data.orderSn = res.data.orderSn;
            Data.orderId = res.data.orderId;
            state.spellOrderId = res.data.spellOrderId || '';
            if (Data.orderId) {
                /***************埋点代码开始********************/
                const traceGoodsList = [];
                Data.goodsList.map(item => {
                    traceGoodsList.push({
                        productId: item.goodsId,
                        productName: item.goodsName,
                        skuId: item.skuId,
                        goodsPrice: item.skuPrice,
                        goodsNumber: item.quantity
                    });
                });
                traceReport('submit_order', {
                    orderId: Data.orderId,
                    // 该金额现在用的是实付金额字段，以后需要有个用于表示GMV的字段替换
                    orderAmount: Data.confirmInfo.orderAmountTotal,
                    payAccount: Data.confirmInfo.orderAmountTotal,
                    payResult: '',
                    goods: traceGoodsList
                });
                /***************埋点代码结束********************/
                if (Data.confirmInfo.orderAmountTotal > 0) {
                    payChannelList();
                } else {
                    router.redirectTo({
                        url: `/pages-cart/paystatus/index?orderId=${Data.orderId}&type=1`
                    });
                }
            }
            if (res.data && res.data.length) {
                let info = res.data.find(el => el.errorMsg) || {};
                Data.stockList = res.data.filter(el => info.errorMsg == el.errorMsg);
                Data.stockPopText = info.errorMsg;
            }
        })
        .catch(err => {
            uni.showToast({
                title: err.data.msg,
                icon: 'none'
            });
            getConfirm();
        });
};

const payChannelList = async () => {
    let res = await request('payChannelListServ');
    let payChannel = res.data.payList?.[0];
    wxPay(payChannel);
    /***************埋点代码开始********************/
    traceReport('pay_order', {
        orderId: Data.orderId,
        payAccount: Data.confirmInfo.orderAmountTotal,
        payResult: ''
    });
    /***************埋点代码结束********************/
};
const payValide = async () => {
    if (Data.tabValue === 0 && !Data.addressId) {
        uni.showToast({
            title: '请选择收货地址',
            icon: 'none'
        });
        orderFlag.value = false;
        return;
    }
    if (Data.tabValue === 1 && !Data.siteId) {
        uni.showToast({
            title: '请选择自提点',
            icon: 'none'
        });
        orderFlag.value = false;
        return;
    }
    if (Data.tabValue === 1 && !Data.consignee) {
        uni.showToast({
            title: '请填写联系人',
            icon: 'none'
        });
        orderFlag.value = false;
        return;
    }
    if (Data.tabValue === 1 && !isMobile(Data.consigneeMobile)) {
        uni.showToast({
            title: '请填写正确的提货人手机号',
            icon: 'none'
        });
        orderFlag.value = false;
        return;
    }
    await subscribe('order_payment');
    // 发起拼团校验
    if (props.orderType == 3 && props.spellOrderId) {
        try {
            const res = await request('getOffereCheckGroupServ', { spellOrderId: props.spellOrderId });
            orderSubmit();
            return;
        } catch (error) {
            switch (error.data.code) {
                case 4000003:
                    uni.showModal({
                        content: error.data.msg,
                        cancelText: '进店逛逛',
                        confirmText: '重新参与',
                        confirmColor: '#FF4D4F',
                        success: e => {
                            if (e.confirm) {
                                toGoodsDetail();
                            } else {
                                toHome();
                            }
                        }
                    });
                    break;
                case 4000004:
                    uni.showModal({
                        content: error.data.msg,
                        cancelText: '进店逛逛',
                        confirmText: '重新参与',
                        confirmColor: '#FF4D4F',
                        success: e => {
                            if (e.confirm) {
                                toGoodsDetail();
                            } else {
                                toHome();
                            }
                        }
                    });
                    break;
                case 4000005:
                    uni.showModal({
                        content: error.data.msg,
                        cancelText: '进店逛逛',
                        confirmText: '重新参与',
                        confirmColor: '#FF4D4F',
                        success: e => {
                            if (e.confirm) {
                                toGoodsDetail();
                            } else {
                                toHome();
                            }
                        }
                    });
                    break;
                default:
                    uni.showToast({
                        title: error.data.msg,
                        icon: 'none',
                        duration: 3000
                    });
                    break;
            }
        }
        // 4000003 该团已失效，请重新选择,4000004 活动已结束，下次早点来哦 4000005 该团已满，请重新选择,4000006 仅新用户可参团，你不符合参团
    } else {
        orderSubmit();
    }
};
const wxPay = async val => {
    let params = {
        orderSn: Data.orderSn,
        payMethod: val.type
    };
    let res;
    try {
        res = await request('payPrepayServ', params);
    } catch (err) {
        orderFlag.value = false;
        if ([9002110, 9002109].includes(err.data?.code)) {
            Dialog.content = err.data?.msg || '网络错误，请稍后重试~';
            messagebox.value.openPopup();
        } else {
            uni.showToast({
                title: err.data?.msg || '网络错误，请稍后重试~',
                icon: 'none',
                duration: 2000
            });
        }
        return;
    }
    let obj = res.data || {};
    // isPaymentApp=true: 商户绑定了支付小程序且开通了宝付支付
    if (res.data?.isPaymentApp) {
        router.redirectTo({
            url: `/pages-cart/cashier/index?appId=${obj.appId}&amount=${Data.confirmInfo.orderAmountTotal}&orderSn=${Data.orderSn}&payMethod=${val.type}&orderId=${Data.orderId}&orderType=${props.orderType}&type=1`
        });
    } else {
        uni.requestPayment({
            provider: 'wxpay',
            timeStamp: obj.timeStamp,
            nonceStr: obj.nonceStr,
            package: obj.package,
            signType: obj.signType,
            paySign: obj.paySign,
            success: function (res) {
                router.redirectTo({
                    url: `/pages-cart/paystatus/index?orderId=${Data.orderId}&orderType=${props.orderType}`
                });
            },
            fail: async err => {
                await request('payCancelServ', { orderSn: Data.orderSn, payMethod: val.type });
                if (err.errMsg == 'requestPayment:fail cancel') {
                    uni.showModal({
                        content: '是否放弃本次付款？',
                        cancelText: '稍后付款',
                        confirmText: '继续付款',
                        confirmColor: '#FE292B',
                        success: async res => {
                            if (res.cancel) {
                                await subscribe('order_non_payment');
                                router.redirectTo({
                                    url: `/pages-user/orderdetail/index?orderId=${Data.orderId}`
                                });
                            }
                            if (res.confirm) {
                                wxPay(val);
                            }
                        }
                    });
                } else {
                    router.redirectTo({
                        url: `/pages-cart/paystatus/index?orderId=${Data.orderId}&type=2`
                    });
                }
            }
        });
    }
};

const getDefalutSelfPick = async () => {
    uni.getLocation({
        type: 'gcj02',
        complete: async res => {
            const { data } = await request('getSiteListServ', {
                lng: res.longitude || 0,
                lat: res.latitude || 0,
                page: 1,
                perPage: 100
            });
            const obj = (data?.list || [])[0] || {};
            Data.siteId = obj.siteId;
            Data.siteListLength = data.totalCount;
            Data.selfAddressInfo = Object.assign(obj, {
                selfLiftName: obj.siteName,
                businessTime: obj.siteInfo
            });
            getConfirm();
        }
    });
};

const cancelOrderConfirm = async () => {
    /*************埋点代码开始***********************/
    const traceGoodsList = [];
    Data.goodsList.map(item => {
        traceGoodsList.push({
            productId: item.goodsId,
            productName: item.goodsName,
            skuId: item.skuId
        });
    });
    traceReport('cancel_order', {
        orderId: Data.orderId,
        goods: traceGoodsList
    });
    /*************埋点代码结束***********************/
    const res = await request('orderCancelServ', {
        shopId: uni.getStorageSync('ZW_SHOP_ID'),
        orderId: Data.orderId
    });
    if (res.data) {
        messagebox?.value?.closePopup();
        router.redirectTo({
            url: `/pages-user/orderdetail/index?orderId=${Data.orderId}`
        });
    }
};

const closeCouponDialog = () => {
    Data.showCoupon = false;
    if (goodsStore.isCouponPage) {
        goodsStore.isCouponPage = false;
        let info = goodsStore.couponList.find(el => el.active) || {};
        Data.customerCouponId = info.customerCouponId || -1;
        getConfirm();
    }
};

onUnload(() => {
    goodsStore.isCouponPage = false;
    goodsStore.addressId = '';
    goodsStore.siteId = '';
});

onShow(async () => {
    closeCouponDialog();
    // here:重新选择自提点，1.后端返回 2.自己查接口  tab切换时地址检查
    if (goodsStore.siteId) {
        Data.siteId = goodsStore.siteId;
        Data.selfAddressInfo = Object.assign(goodsStore.siteObj, {
            selfLiftName: goodsStore.siteObj.siteName,
            businessTime: goodsStore.siteObj.siteInfo
        });
    }
    // 重新选择地址
    if (Data.addressId || goodsStore.addressId) {
        Data.addressId = goodsStore.addressId ? goodsStore.addressId : Data.addressId;
        getConfirm();
    }
});
</script>
<style lang="scss" scoped src="./index.scss"></style>
